package org.hot100_5.leetcode56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public int[][] merge(int[][] intervals) {
        int n1 = intervals.length;
        Arrays.sort(intervals, (arr1, arr2) -> arr1[0] - arr2[0]);

        List<int[]> list = new ArrayList<>();
        int start = intervals[0][0];
        int end = intervals[0][1];

        for (int i = 1; i < n1; i++) {
            if (intervals[i][0] > end) {
                int [] temp = new int[2];
                temp[0]=start;
                temp[1]=end;
                list.add(temp);
                start=intervals[i][0];
                end = intervals[i][1];
            }else {
                end = Math.max(end,intervals[i][1]);
            }
        }
        int [] temp = {start,end};
        list.add(temp);

        int [][] res= new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            res[i]=list.get(i);
        }
        return res;
    }
}
